package org.rbac.content;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;


/**
 * 
*  <pre>    
* 类名称：CacheContent 
* 类描述：   缓存容器
* 创建人：陈国祥   (kingschan)
* 创建时间：2015-6-12 下午3:05:31   
* 修改人：Administrator   
* 修改时间：2015-6-12 下午3:05:31   
* 修改备注：   
* @version V1.0
* </pre>
 */
public class CacheContent extends ApplicationContent{
    private static Logger log = Logger.getLogger(CacheContent.class);
    private static CacheContent instance;
    private static CacheManager cacheManager ;
    private static Map<CONTENT, Cache> cache;
    private CacheContent(){    }
    
    public synchronized static CacheContent getInstance(){
        if (null==instance) {
            instance=new CacheContent();
            cacheManager= CacheManager.create(instance.getClass().getResource("/ehcache.xml")); 
           Iterator<CONTENT> itera= contentMapping.keySet().iterator();
           cache= new HashMap<ApplicationContent.CONTENT, Cache>();
           while (itera.hasNext()) {
               CONTENT content=itera.next();
               log.debug("inital cache content:"+content);
               Cache c =cacheManager.getCache(contentMapping.get(content));
               cache.put(content, c);
            
           }
        }
        return instance;
    }

    @Override
    public void init() {
        
        
    }

    @Override
    public void shutdown() {
        log.info("关闭缓存容器");
        cacheManager.shutdown();
        
    }

    @Override
    public Object get(String key,CONTENT target) {
        log.info("读取:"+key+" | 内存占用 "+getMemoryStoreSize(target)+"kb");
        return null==cache.get(target).get(key)?null:cache.get(target).get(key).getObjectValue();
    }

    @Override
    public void put(String key, Object value,CONTENT target) {
        log.info("=====<<||>>==============设置:"+key);
        cache.get(target).put(new Element(key, value));
        
    }

    @Override
    public void remove(String key,CONTENT target) {
        cache.remove(key);
    }

    @Override
    public void removeAll(CONTENT target) {
        cache.get(target).removeAll();
        
    }

    @Override
    public Long getMemoryStoreSize(CONTENT target) {
        
        return  cache.get(target).getMemoryStoreSize();
    }

    @Override
    public Integer getSize(CONTENT target) {
        return cache.get(target).getSize();
    }

}
